<template>
    <el-form class="el-fr-form" :label-width="setAttr('labelWidth', '120px')" :rules="setAttr('rules', {})" :ref="refsName">
        <slot></slot>
    </el-form>
    
</template>

<script>
import { ref, toRef } from 'vue'
export default {
    name: 'Form',
    props: {
        item: {
            type: Object,
            default: function () {
                return {}
            }
        },
        value: null
    },
    emits: ['update:modelValue'],
    setup(props, context) {
        // 双向绑定数据
        let modelValue = ref([])
        let refsName = ref('form' + strLen())
        const item = toRef(props, 'item')
        function setAttr(name, value = '') {
            if (Object.prototype.hasOwnProperty.call(item.value.attribute, name) && item.value.attribute[name].extendData) {
                return item.value.attribute[name].extendData
            }
            return Object.prototype.hasOwnProperty.call(item.value.attribute, name) ? item.value.attribute[name].value : value
        }
        function strLen() {
            var str = '';
            for(var i = 0; i<16; i++) {
                str += (Math.floor((Math.random()*15)+1)).toString(16);
            }
            return str;
        }
        return {
            modelValue,
            setAttr,
            refsName
        }
    },
    watch: {
        value: {
            handler(v) {
                if (v && v !== '') {
                    try {
                        this.formRes = JSON.parse(v)
                    } catch (e) {
                        console.log(e)
                    }
                } else {
                    this.formRes = {}
                }
            },
            deep: true,
            immediate: true
        },
        modelValue: {
            handler(v) {
                if (!v) {
                    return
                }
                this.$emit('update:modelValue', { value: JSON.stringify(v) })
            },
            deep: true
        }
    },
    methods: {},
    mounted() {}
}
</script>

<style></style>
